<?php
// +----------------------------------------------------------------------
// | CSMITSM  [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2024 https://www.fastadmin.net All rights reserved.
// +----------------------------------------------------------------------
// | Author: chenshiming
// +----------------------------------------------------------------------

namespace app\admin\controller\csmitsm;

use addons\csmitsm\library\sdnode\xstack\utils\XsJsonUtils;
use addons\csmitsm\library\xcore\xcflow\utils\XcflowallformUtils;
use think\Db;
use Exception;
use addons\csmitsm\library\xcore\xcore\base\XcABackend;
use addons\csmitsm\library\xcore\xcore\utils\XcRequestUtils;
use addons\csmitsm\library\xcore\xcore\utils\XcDatabaseUtils;
use addons\csmitsm\library\xcore\xcore\utils\XcResponseUtils;

/**
 * 数据库视图
 *
 * @icon fa fa-circle-o
 */
class Xcflowdbview extends XcABackend
{

    /**
     * Xcflowdbview模型对象
     * @var \app\admin\model\csmitsm\Xcflowdbview
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\csmitsm\Xcflowdbview;
        $this->assign("statusList", $this->model->getStatusList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

     public function edit($ids = null)
     {
         $row = $this->model->get($ids);
         if (!$row) {
             $this->error(__('No Results were found'));
         }
         $adminIds = $this->getDataLimitAdminIds();
         if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
             $this->error(__('You have no permission'));
         }
         if (false === $this->request->isPost()) {
            
            // append field while fieldjson lack 
            if(true){
                $fields = XcDatabaseUtils::queryTablefieldList($row->viewname);
                // $fieldjsonObj = json_decode($row->fieldjson, true);
                // $fieldjsonObj = ($fieldjsonObj)?$fieldjsonObj:[];
                $fieldjsonObj = XsJsonUtils::stringToJson($row->fieldjson);
                foreach($fields as $field){
                    $isFound = false;
                    foreach($fieldjsonObj as $jsonitem){
                        if(strtolower($field['name'])==strtolower($jsonitem['column'])){
                            $isFound = true;
                        }
                    }
                    if($isFound===false){
                        $fieldjsonObj[] = [
                            "column"=>$field['name'],
                            "tablename"=>null,
                            "tablecolumn"=>null,
                        ];
                    }
                }
                $row['fieldjson'] = XsJsonUtils::jsonToString($fieldjsonObj);
            }


             $this->view->assign('row', $row);
             return $this->view->fetch();
         }
         $params = $this->request->post('row/a');
         if (empty($params)) {
             $this->error(__('Parameter %s can not be empty', ''));
         }
         $params = $this->preExcludeFields($params);
         $result = false;
         Db::startTrans();
         try {
             //是否采用模型验证
             if ($this->modelValidate) {
                 $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                 $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                 $row->validateFailException()->validate($validate);
             }
             if(true){
                // $fieldjson = json_decode($params['fieldjson'], true);
                $fieldjson = XsJsonUtils::stringToJson($params['fieldjson']);
                foreach($fieldjson as &$field){
                    if(!empty($field['tablename']) && empty($field['tablecolumn'])){
                        $list = XcDatabaseUtils::queryTablefieldList($field['tablename']);

                        foreach($list as $item){
                            if($item['name']==$field['column']){
                                $field['tablecolumn'] = $field['column'];
                                break;
                            }
                        }
                    }
                }
                $params['fieldjson'] = XsJsonUtils::jsonToString($fieldjson);
             }



             $result = $row->allowField(true)->save($params);
             Db::commit();
         } catch (Exception $e) {
             Db::rollback();
             $this->error($e->getMessage());
         }
         if (false === $result) {
             $this->error(__('No rows were updated'));
         }
         $this->success();
     }

    public function selectTables()
    {
        $keyValue = XcRequestUtils::get("keyValue");
        if ($keyValue) {
            return [
                'total' => 1,
                'list' => [
                    ['tablename' => $keyValue]
                ]
            ];
        }
        $tables = XcflowallformUtils::queryTableinfoList([['xcformtype', 'in', ['flow', 'flowsub', 'mdm']]]);
        
        $list = [];
        foreach ($tables as $item) {
            $list[] = [
                'tablename' => $item['tablename'],
                'displayname' => $item['name'] . ' ' . $item['tablename']
            ];
        }
        return XcResponseUtils::selectpage($list);
    }

    public function selectTablefields()
    {
        $keyValue = XcRequestUtils::get("keyValue");
        if ($keyValue) {
            return [
                'total' => 1,
                'list' => [
                    ['name' => $keyValue]
                ]
            ];
        }
        $tablename = XcRequestUtils::get("tablename");
        $list = XcDatabaseUtils::queryTablefieldList($tablename);
        return XcResponseUtils::selectpage($list);
    }
    public function selectTablefields2()
    {
        $tablename = XcRequestUtils::get("tablename");
        $list = XcDatabaseUtils::queryTablefieldList($tablename);
        $this->success(null,null,['list'=>$list]);
    }

}
